//
//  DCIMGroupManager.m
//  xmppBase
//
//  Created by striby on 16/1/12.
//  Copyright © 2016年 com.dc. All rights reserved.
//

#import "DCIMGroupManager.h"
@interface DCIMGroupManager()
{
    
}

@property(nonatomic,strong)NSMutableDictionary * createdOrJoinedGroups;
//@property(nonatomic,strong)XMPPMUC * xmppMuc ;

@end
@implementation DCIMGroupManager
+(DCIMGroupManager *)shareInstance
{
    static DCIMGroupManager * instance= nil;
    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
        instance = [[self alloc]init];
//        instance.groupQue = dispatch_queue_create("com.dc.im.group", NULL);
        instance.groupQue = dispatch_get_global_queue(2, 0);
        instance.createdOrJoinedGroups = [[NSMutableDictionary alloc]initWithCapacity:1];
    });
    
    return instance;
}

-(XMPPRoom *)createRoomWithRoomJid:(XMPPJID *)roomId
{
    
    if ([_createdOrJoinedGroups.allKeys containsObject:roomId.full]) {
        return [_createdOrJoinedGroups objectForKey:roomId.full];
    }
    
    
    XMPPRoom * _room = [[XMPPRoom alloc]initWithRoomStorage:self jid:roomId];

    [_room activate:[DCXMPPTool shareInstance].xmppStream];
    
    [_room addDelegate:self delegateQueue:self.groupQue];
    
    [_createdOrJoinedGroups setObject:_room forKey:roomId.full];
    
    return _room;
}

-(XMPPRoom*)joinRoomWithRoomJid:(XMPPJID *)roomId
{
    
    
    XMPPRoom * room =  [self createRoomWithRoomJid:roomId];
    
    DCXMPPTool * xmppTool = [DCXMPPTool shareInstance];
    
    XMPPvCardTemp * card = [xmppTool.xmppvCardTempModule vCardTempForJID:xmppTool.xmppStream.myJID shouldFetch:YES];
    
    [room joinRoomUsingNickname:card.nickname history:nil];
    
    return room;
}


-(void)queryInfoJid:(NSString *)jid{
    DCXMPPTool * xmppTool = [DCXMPPTool shareInstance];
    XMPPIQ* iq=[XMPPIQ iqWithType:@"get"];
    [iq addAttributeWithName:@"from" stringValue:xmppTool.xmppStream.myJID.bare];
    [iq addAttributeWithName:@"id" stringValue:@"disco-1"];
    [iq addAttributeWithName:@"to" stringValue:jid];
    NSXMLElement* element_query=[NSXMLElement elementWithName:@"query" xmlns:@"http://jabber.org/protocol/disco#info"];
    [iq addChild:element_query];
    [xmppTool.xmppStream sendElement:iq];
}
-(void)queryItemsJid:(NSString *)jid{
    DCXMPPTool * xmppTool = [DCXMPPTool shareInstance];
    
    XMPPIQ* iq=[XMPPIQ iqWithType:@"get"];
    [iq addAttributeWithName:@"from" stringValue:xmppTool.xmppStream.myJID.bare];
    [iq addAttributeWithName:@"id" stringValue:@"disco-3"];
    [iq addAttributeWithName:@"to" stringValue:jid];
    NSXMLElement* element_query=[NSXMLElement elementWithName:@"query" xmlns:@"http://jabber.org/protocol/disco#items"];
    [iq addChild:element_query];
    [xmppTool.xmppStream sendElement:iq];
}

-(NSString *)getRoomNameWithRoomJid:(XMPPJID *)roomId
{
    NSDictionary * info = [self getRoomConfigFormStorageWithInfo:roomId];
    
    return info==nil?nil:[info objectForKey:@"roomname"];
}

-(NSDictionary*)getRoomConfigFormStorageWithInfo:(XMPPJID *)roomJid
{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    return [user objectForKey:roomJid.full];
}

-(void)saveRoomConfigInStorageWithInfo:(id)config withRoom:(XMPPRoom *)room
{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    
    DDXMLElement * ele = config;
    
    for (DDXMLElement * child in ele.children) {
        if ([child attributeForName:@"var"]) {
            if ([[[child attributeForName:@"var"] stringValue]isEqualToString:@"muc#roomconfig_roomname"]) {
                //房间名称
                NSString * roomname =[[child elementForName:@"value"] stringValue];
                [user setObject:@{@"roomname":roomname  } forKey:room.roomJID.full];
                break;
            }
        }
    }
    
    
    
    [user synchronize];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:kDidFetchConfigurationForm object:room userInfo:nil];
    
}
#pragma mark 房间昵称
-(void)setRoomName:(NSString*)name forRoom:(XMPPRoom*)room
{
    NSXMLElement *x = [NSXMLElement elementWithName:@"x" xmlns:@"jabber:x:data"];
    
    NSXMLElement *field = [NSXMLElement elementWithName:@"field"];
    NSXMLElement *value = [NSXMLElement elementWithName:@"value"];
    
    NSXMLElement *valueowners = [NSXMLElement elementWithName:@"value"];
    
    
    [field addAttributeWithName:@"var" stringValue:@"muc#roomconfig_roomname"];
    
    [field addAttributeWithName:@"type" stringValue:@"string"];
    
    
    [value setStringValue:name];
    [valueowners setStringValue:[DCXMPPTool shareInstance].xmppStream.myJID.full]; //创建者的Jid
    
    [x addChild:field];
    [field addChild:value];
    
    
    [room configureRoomUsingOptions:x];

}

#pragma mark - 设置用户权限 owner admin 等高级权限
-(void)setHigherAfficationWithJid:(XMPPJID*)jid forRoom:(XMPPRoom*)room andNick:(NSString * )nick
{
    
//    <iq from='crone1@shakespeare.lit/desktop'
//    id='mod1'
//    to='coven@chat.shakespeare.lit'
//    type='set'>
//    <query xmlns='http://jabber.org/protocol/muc#admin'>
//    <item nick='thirdwitch'
//    role='moderator'/>
//    </query>
//    </iq>
    
    
    XMPPvCardTemp * card = [[DCXMPPTool shareInstance].xmppvCardTempModule vCardTempForJID:jid shouldFetch:YES];
    
    XMPPIQ * iq  = [XMPPIQ iqWithType:@"set" to:room.roomJID elementID:@"owner1"];
   
    DDXMLElement * query = [[DDXMLElement alloc]initWithName:@"query" xmlns:@"http://jabber.org/protocol/muc#admin"];
    
    DDXMLElement * item = [[DDXMLElement alloc]initWithName:@"item"];
    [item addAttributeWithName:@"affiliation" stringValue:@"owner"];
    [item addAttributeWithName:@"jid" stringValue:jid.full];
    
    [query addChild:item];
    
    [iq addChild:query];
    
    [[DCXMPPTool shareInstance].xmppStream sendElement:iq];
    
    
    
}

#pragma mark 配置房间为永久房间
-(void)sendDefaultRoomConfigWithRoom:(XMPPRoom*)room
{
    
    NSXMLElement *x = [NSXMLElement elementWithName:@"x" xmlns:@"jabber:x:data"];
    
    NSXMLElement *field = [NSXMLElement elementWithName:@"field"];
    NSXMLElement *value = [NSXMLElement elementWithName:@"value"];
    
    NSXMLElement *valueowners = [NSXMLElement elementWithName:@"value"];
    
    
    [field addAttributeWithName:@"var" stringValue:@"muc#roomconfig_persistentroom"];  // 永久属性
    
    
    [field addAttributeWithName:@"type" stringValue:@"boolean"];

    
    [value setStringValue:@"1"];
    [valueowners setStringValue:[DCXMPPTool shareInstance].xmppStream.myJID.full]; //创建者的Jid
    
    [x addChild:field];
    [field addChild:value];

    
    [room configureRoomUsingOptions:x];
    

}

#pragma mark - XMPPRoomStorage delegate


-(void)handleIncomingMessage:(XMPPMessage *)message room:(XMPPRoom *)room
{
    NSLog(@"%s",__FUNCTION__);
}

-(void)handleOutgoingMessage:(XMPPMessage *)message room:(XMPPRoom *)room
{
     NSLog(@"%s",__FUNCTION__);
}

-(BOOL)configureWithParent:(XMPPRoom *)aParent queue:(dispatch_queue_t)queue
{
     NSLog(@"%s",__FUNCTION__);
    return YES;
}

-(void)handlePresence:(XMPPPresence *)presence room:(XMPPRoom *)room
{
     NSLog(@"%s",__FUNCTION__);
}

-(void)handleDidLeaveRoom:(XMPPRoom *)room
{
     NSLog(@"%s",__FUNCTION__);
}


#pragma - mark room delegate
-(void)xmppRoom:(XMPPRoom *)sender didConfigure:(XMPPIQ *)iqResult
{
     NSLog(@"%s",__FUNCTION__);
    
    [sender fetchConfigurationForm];
}

-(void)xmppRoom:(XMPPRoom *)sender didEditPrivileges:(XMPPIQ *)iqResult
{
     NSLog(@"%s",__FUNCTION__);
}

-(void)xmppRoom:(XMPPRoom *)sender didFailToDestroy:(XMPPIQ *)iqError
{
     NSLog(@"%s",__FUNCTION__);
}

-(void)xmppRoom:(XMPPRoom *)sender didFetchBanList:(NSArray *)items
{
     NSLog(@"%s",__FUNCTION__);
}

-(void)xmppRoom:(XMPPRoom *)sender didFetchConfigurationForm:(DDXMLElement *)configForm
{
     NSLog(@"%s",__FUNCTION__);
    

    [self saveRoomConfigInStorageWithInfo:configForm withRoom:sender];
}

-(void)xmppRoom:(XMPPRoom *)sender didFetchMembersList:(NSArray *)items
{
     NSLog(@"%s",__FUNCTION__);
}

-(void)xmppRoom:(XMPPRoom *)sender didFetchModeratorsList:(NSArray *)items
{
     NSLog(@"%s",__FUNCTION__);
    
    [[NSNotificationCenter defaultCenter]postNotificationName:kDidFetchModeratorList object:items userInfo:@{@"sender":sender}];
}

-(void)xmppRoom:(XMPPRoom *)sender didReceiveMessage:(XMPPMessage *)message fromOccupant:(XMPPJID *)occupantJID
{
     NSLog(@"%s",__FUNCTION__);
}

-(void)xmppRoom:(XMPPRoom *)sender occupantDidJoin:(XMPPJID *)occupantJID withPresence:(XMPPPresence *)presence
{
     NSLog(@"%s",__FUNCTION__);
    
    DDXMLElement * ele = [presence children][1];
    
    DDXMLElement * item =[ele elementForName:@"item"];
    
    XMPPJID * jid = [XMPPJID jidWithString: [[item attributeForName:@"jid"] stringValue]]   ;
    
    
    
    [self setHigherAfficationWithJid:jid forRoom:sender andNick:nil];
}

-(void)xmppRoom:(XMPPRoom *)sender occupantDidLeave:(XMPPJID *)occupantJID withPresence:(XMPPPresence *)presence
{
     NSLog(@"%s",__FUNCTION__);
}

-(void)xmppRoom:(XMPPRoom *)sender occupantDidUpdate:(XMPPJID *)occupantJID withPresence:(XMPPPresence *)presence
{
     NSLog(@"%s",__FUNCTION__);
}

-(void)xmppRoom:(XMPPRoom *)sender willSendConfiguration:(XMPPIQ *)roomConfigForm
{
     NSLog(@"%s",__FUNCTION__);
}

-(void)xmppRoomDidCreate:(XMPPRoom *)sender
{
     NSLog(@"%s",__FUNCTION__);
    
    [self sendDefaultRoomConfigWithRoom:sender];

    
    
    XMPPvCardTemp * mycard = [[DCXMPPTool shareInstance].xmppvCardTempModule vCardTempForJID:[DCXMPPTool shareInstance].xmppStream.myJID shouldFetch:YES];
    
    [self setRoomName:[NSString stringWithFormat:@"%@创建的群",mycard.nickname] forRoom:sender];
    
    if ([[mycard getJoinedGroup] lastObject]) {
        DDXMLElement * group = [[mycard getJoinedGroup] lastObject];
        
        if ([[group stringValue]isEqualToString:sender.roomJID.full ]) {
            return;
        }
     
    }
    
    
    
    [mycard addCreatedGroup:sender.roomJID];
    
    [[DCXMPPTool shareInstance].xmppvCardTempModule updateMyvCardTemp:mycard];
    
    NSString * firstMessage =[NSString  stringWithFormat:@"%@成功创建了群",mycard.nickname];
    
    [DCMessageSender messageWithMessageType:groupMessage andSubType:textMessage forString:firstMessage addtionXMLs:nil  toUser:sender.roomJID autoSendToServer:YES];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:kDidCreatedGroupSuccessed object:nil];


    
}

-(void)xmppRoomDidDestroy:(XMPPRoom *)sender
{
     NSLog(@"%s",__FUNCTION__);
}

-(void)xmppRoomDidJoin:(XMPPRoom *)sender
{
     NSLog(@"%s",__FUNCTION__);
    
    [sender fetchConfigurationForm];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:kDidJoinGroupSuccessed object:nil];
}

-(void)xmppRoomDidLeave:(XMPPRoom *)sender
{
     NSLog(@"%s",__FUNCTION__);
}



@end
